import type { Params } from '@/components/Table';
import XcTable from '@/components/Table';
import { getButtonPermissions } from '@/utils/utils';
import type { ActionType } from '@ant-design/pro-table';
import { Access } from '@umijs/max';
import type { FormInstance } from 'antd';
import { Button, message, Modal } from 'antd';
import React, { MutableRefObject, useCallback, useEffect, useRef, useState } from 'react';

// 按钮配置接口
interface ButtonConfig {
  key: string;
  text: string;
  type?: 'primary' | 'default' | 'dashed' | 'link' | 'text';
  permission?: string;
  onClick?: () => void;
  icon?: React.ReactNode;
  disabled?: boolean;
}

// 页面配置接口
interface CommonPageConfig {
  // 表格字段配置
  fields: any[];
  // 数据获取函数
  getDataSource: (params: Params) => Promise<any>;
  // 工具栏按钮配置
  toolbarButtons?: ButtonConfig[];
  // 行选择配置
  rowSelection?: boolean | any;
  // 行键
  rowKey?: string;
  // 搜索参数
  searchParams?: any;
  // 表格标题
  title?: string;
  // 是否显示工具栏
  showToolbar?: boolean;
  // 自定义头部组件
  header?: React.ReactNode;
}

interface CommonPageProps {
  config: CommonPageConfig;
}

const CommonPage: React.FC<CommonPageProps> = ({ config }) => {
  // Refs
  const tableRef = useRef<ActionType>();
  const tableFormRef = useRef() as MutableRefObject<FormInstance<any>>;

  // States
  const [params] = useState(config.searchParams || {}); // 搜索条件
  const [tableFields, setTableFields] = useState<any[]>([]);

  // Context holders
  const [, messageContextHolder] = message.useMessage();
  const [, modalContextHolder] = Modal.useModal();

  // Permissions
  const btnPermissions = getButtonPermissions();

  /**
   * 获取页面配置
   */
  const getPageConfig = useCallback(async () => {
    try {
      // 设置表格字段
      setTableFields(config.fields);
    } catch (error) {
      console.error('获取页面配置失败:', error);
      message.error('页面配置加载失败');
    }
  }, [config.fields]);

  /**
   * 渲染工具栏按钮
   */
  const renderToolbarButtons = useCallback(() => {
    if (!config.showToolbar && !config.toolbarButtons?.length) {
      return [];
    }

    return (
      config.toolbarButtons?.map((button) => {
        const isAccessible = button.permission ? btnPermissions.includes(button.permission) : true;

        return (
          <Access key={button.key} accessible={isAccessible}>
            <Button
              type={button.type || 'default'}
              onClick={button.onClick}
              icon={button.icon}
              disabled={button.disabled}
            >
              {button.text}
            </Button>
          </Access>
        );
      }) || []
    );
  }, [config.toolbarButtons, config.showToolbar, btnPermissions]);

  // 初始化页面配置
  useEffect(() => {
    getPageConfig();
  }, [getPageConfig]);

  return (
    <>
      <XcTable
        getDataSource={config.getDataSource}
        fields={tableFields}
        actionRef={tableRef}
        formRef={tableFormRef}
        params={params}
        rowKey={config.rowKey || 'id'}
        rowSelection={config.rowSelection || false}
        toolBarRender={renderToolbarButtons}
        headerTitle={config.header}
      />
      {messageContextHolder}
      {modalContextHolder}
    </>
  );
};

export default CommonPage;
